# Cart routes
from flask import Blueprint, request, jsonify, session
from app.models.cart import (
    get_cart_items, add_to_cart, update_cart_item, 
    remove_cart_item, clear_cart
)
from app.models.product import get_product_by_id

cart_bp = Blueprint('cart', __name__)

@cart_bp.route('/cart', methods=['GET'])
def get_cart():
    """Get cart"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    try:
        cart_items = get_cart_items(user_id)
        cart_data = []
        total_price = 0
        
        for item in cart_items:
            product = get_product_by_id(item['category'], item['product_id'])
            if product:
                item_data = dict(item)
                item_data['product'] = product
                item_data['subtotal'] = float(product['price']) * item['quantity']
                # No need for additional settings, use cart_id directly
                cart_data.append(item_data)
                total_price += item_data['subtotal']
        
        return jsonify({
            'items': cart_data,
            'total_price': total_price,
            'total_items': len(cart_data)
        })
    except Exception as e:
        return jsonify({'error': f'Failed to get cart: {str(e)}'}), 500

@cart_bp.route('/cart/add', methods=['POST'])
def add_to_cart_api():
    """Add product to cart"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Please provide product information'}), 400
    
    category = data.get('category')
    product_id = data.get('product_id')
    quantity = data.get('quantity', 1)
    
    if not category or not product_id:
        return jsonify({'error': 'Please provide product category and ID'}), 400
    
    if quantity <= 0:
        return jsonify({'error': 'Quantity must be greater than 0'}), 400
    
    # Verify product exists
    product = get_product_by_id(category, product_id)
    if not product:
        return jsonify({'error': 'Product does not exist'}), 404
    
    # Check stock
    if product['stock'] < quantity:
        return jsonify({'error': 'Insufficient stock'}), 400
    
    # Check if cart is full (max 5 different products)
    cart_items = get_cart_items(user_id)
    if len(cart_items) >= 5:
        return jsonify({'error': 'Cart is full, maximum 5 different products allowed'}), 400
    
    try:
        add_to_cart(user_id, category, product_id, quantity)
        return jsonify({'success': True, 'message': 'Add successful'})
    except ValueError as e:
        return jsonify({'success': False, 'error': str(e)}), 400
    except Exception as e:
        return jsonify({'success': False, 'error': f'Add failed: {str(e)}'}), 500

@cart_bp.route('/cart/<int:cart_item_id>', methods=['PUT'])
def update_cart_item_api(cart_item_id):
    """Update cart item quantity"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    data = request.get_json()
    quantity = data.get('quantity')
    
    if quantity is None:
        return jsonify({'error': 'Please provide quantity'}), 400
    
    if quantity < 0:
        return jsonify({'error': 'Product quantity cannot be negative'}), 400
    
    try:
        update_cart_item(cart_item_id, user_id, quantity)
        return jsonify({'message': 'Update successful'})
    except ValueError as e:
        return jsonify({'error': str(e)}), 400
    except Exception as e:
        return jsonify({'error': f'Update failed: {str(e)}'}), 500

@cart_bp.route('/cart/<int:cart_item_id>', methods=['DELETE'])
def remove_cart_item_api(cart_item_id):
    """Remove cart item"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    try:
        remove_cart_item(cart_item_id, user_id)
        return jsonify({'message': 'Remove successful'})
    except Exception as e:
        return jsonify({'error': f'Remove failed: {str(e)}'}), 500

@cart_bp.route('/cart', methods=['DELETE'])
def clear_cart_api():
    """Clear cart"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    try:
        clear_cart(user_id)
        return jsonify({'message': 'Cart cleared'})
    except Exception as e:
        return jsonify({'error': f'Clear failed: {str(e)}'}), 500
